<template>
  <div>
    <el-tree
      :data="roleMenus"
      :props="defaultProps"
      @node-click="handleNodeClick"
      ref="menu-tree"
      show-checkbox
      default-expand-all
      :default-checked-keys="checkedIds"
      node-key="id"
    ></el-tree>
    <el-button @click="onSave">保存</el-button>
    <el-button @click="handleClear">清空</el-button>
  </div>
</template>
<script>
import { getRoleMenus, setRoleMenus } from '@/api/role'

export default {
  name: 'RoleAllocMenu',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      // 角色菜单信息
      checkedIds: [],
      roleMenus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      }
    }
  },
  created () {
    this.loadRoleMenus()
  },
  methods: {
    onSave () {
      const data = {
        roleId: this.roleId,
        menuIdList: this.$refs['menu-tree'].getCheckedKeys()
      }
      setRoleMenus(data).then((res) => {
        if (res.data.code === '000000') {
          this.$message.success('给角色分配菜单操作成功')
          this.$router.push({ name: 'roles' })
        } else {
          this.$message.error('分配菜单操作失败')
        }
      })
    },
    handleClear () {
      this.$refs['menu-tree'].setCheckedKeys([])
    },
    loadRoleMenus () {
      getRoleMenus(this.roleId).then((res) => {
        if (res.data.code === '000000') {
          this.roleMenus = res.data.data
          //  const checkedIds =
          this.checkedIds = this.getSelectedIds(res.data.data)
          //   这样也行
          //   this.$nextTick(() => {
          //     this.$refs["menu-tree"].setCheckedKeys(checkedIds);
          //   });
        } else {
          this.$message.error('获取角色菜单信息失败')
        }
      })
    },
    // 已选中的id
    getSelectedIds (menuArr) {
      let ids = []
      menuArr.forEach((menu) => {
        if (menu.subMenuList) {
          const tmpArr = this.getSelectedIds(menu.subMenuList)
          ids = ids.concat(tmpArr)
        } else if (menu.selected) {
          ids.push(menu.id)
        }
      })
      return ids
    },
    handleNodeClick (data) {
      console.log(data)
    }
  }
}
</script>
<style scoped lang="scss">
.el-tree {
  margin-bottom: 20px;
}
</style>
